<template>
<div id="map-container">
    <MapDraw @circle="drawCircle" @point="drawPoint" @polyline="drawPolyline" @polygon="drawPolygon" @end="drawOff"></MapDraw>
</div>
</template>

<script>
import L from "leaflet"; //引入地图api
import "leaflet/dist/leaflet.css"; //引入地图样式
// 注意：
// 一定要在 leaflet.js 成功引入之后，在引用此插件
import "leaflet-measure-path";
import "leaflet-measure-path/leaflet-measure-path.css";
import MapDraw from "./MapDraw";
// 解决 leaflet 默认 maker 无法显示的问题
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";

export default {
    name: "maptest",
    components: {
        MapDraw,
    },
    data() {
        //私有变量
        return {
            map: null,
            overLayer: {
                polylines: [],
                polygons: [],
            },
            tempGp: {
                lineNode: [],
                lineNodeLen: 0,
                tempLine: null,
                tempNode: [],
                polygonNode: [],
                polygonNodeLen: 0,
                tempNode: [],
                tempPolygon: null,
                tempCircle: null,
            },
            activeTool: "",
        };
    },

    mounted() {
        this.map = L.map("map-container", {
            crs: L.CRS.EPSG4326,
            center: {
                lon: 112,
                lat: 40,
            },
            zoom: 13,
        }); //声明地图对象。
        //在函数内访问组件的私有变量，怎么实现？
        //用_self替换this
        this.addLayer();
        this.map.setView([39.5, 116.4], 8); //设置地图的中心和缩放等级
        console.log(this.map);
    },
    methods: {
        addLayer: async function () {
            let t1 = L.tileLayer(
                "http://t1.tianditu.com/vec_c/wmts?layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=2d071151ca08ae20687e322737734ad5", {
                    maxZoom: 20,
                    tileSize: 256,
                    zoomOffset: 1,
                }
            );
            let t2 = L.tileLayer(
                "http://t1.tianditu.com/img_c/wmts?layer=img&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=2d071151ca08ae20687e322737734ad5", {
                    maxZoom: 20,
                    tileSize: 256,
                    zoomOffset: 1,
                }
            );
            let baseMaps = {
                矢量: t1,
                影像: t2,
            };

            t1.addTo(this.map);
            L.control.layers(baseMaps).addTo(this.map);

            let url = "http://123.57.54.225:4001/geojson/XZQH_CITY.json";
            url = "/data/bjrailway.geojson";
            this.$api.get(url, {}, (response) => {
                console.log(response);
                L.geoJSON(response.data, {
                        style: function (feature) {
                            return {
                                color: "red",
                            };
                        },
                    })
                    .bindPopup(function (layer) {
                        return (
                            layer.feature.properties.name +
                            layer.feature.properties.Shape_Length +
                            "米"
                        );
                    })
                    .addTo(this.map);
            });
        },
        zoomIn() {
            this.map.zoomIn();
        },
        zoomOut() {
            this.map.zoomOut();
        },
        resetMap() {
            //
            this.map.setView([51.505, -0.09], 13);
        },
        addMarker: function (coordinate) {
            let DefaultIcon = L.icon({
                iconUrl: icon,
                shadowUrl: iconShadow,
            });

            let marker = L.marker(L.latLng(coordinate[0], coordinate[1]), {
                icon: DefaultIcon,
            });
            marker.addTo(this.map);
        },
        addPolyline(linePath) {
            let polyline = L.polyline(linePath, {
                stroke: true,
                color: "#0085fb",
                weight: 4,
                opacity: 0.7, //不透明度
            });
            polyline.addTo(this.map);
        },
        addPolygon(areapath) {
            let polygon = L.polygon(areapath, {});
            polygon.addTo(this.map);
        },
        drawOn(fn) {
            // 监听地图点击事件
            this.map.off("click");
            //   this.map.on("click", evt => fn(evt));
            this.map.off("mousemove");
            this.map.off("dblclick");
            this.map.doubleClickZoom.disable();
        },
        drawPt(fn) {
            // 监听地图点击事件
            this.map.off("click");
            this.map.on("click", (evt) => fn(evt));
            this.map.off("mousemove");
            this.map.off("dblclick");
            this.map.doubleClickZoom.disable();
        },
        drawOff() {
            // 移除监听地图点击事件
            this.map.off("click");
            this.map.off("mousemove");
            this.map.off("dblclick");
            this.map.doubleClickZoom.enable();
        },
        drawPoint() {
            console.log("画点");
            this.drawPt((evt) => {
                this.addNode(evt.latlng, this.map);
                let popup = L.popup()
                    .setLatLng(evt.latlng)
                    .setContent("纬度：" + evt.latlng.lat + "经度：" + evt.latlng.lng)
                    .openOn(this.map);
            });
        },
        drawPolyline() {
            let tempPolygonOpts = {
                color: "rgba(255, 0, 0, 0.85)",
                weight: 3,
                opacity: 0.85,
            };

            let finalPolygonOpts = {
                color: "rgba(0, 255, 0, 0.85)",
                weight: 3,
                opacity: 0.85,
            };
            this.drawOn();

            this.map.on("click", (evt) => {
                this.tempGp.lineNode.push([evt.latlng.lat, evt.latlng.lng]);
                this.tempGp.tempNode.push(this.addNode(evt.latlng, this.map));
                this.tempGp.lineNodeLen = this.tempGp.lineNode.length;
            });

            this.map.on("mousemove", (evt) => {
                if (this.tempGp.lineNodeLen >= 1) {
                    if (this.tempGp.tempLine) this.tempGp.tempLine.remove();
                    this.tempGp.lineNode[this.tempGp.lineNodeLen] = [
                        evt.latlng.lat,
                        evt.latlng.lng,
                    ];

                    this.tempGp.tempLine = L.polyline(
                        this.tempGp.lineNode,
                        tempPolygonOpts
                    );
                    this.tempGp.tempLine.addTo(this.map);
                }
            });

            this.map.on("dblclick", () => {
                let polyline = L.polyline(this.tempGp.lineNode, finalPolygonOpts);
                polyline.addTo(this.map);
                this.overLayer.polylines.push(polyline);
                this.tempGp.lineNode = [];
                this.tempGp.lineNodeLen = 0;
                this.tempGp.tempLine.remove();
                this.tempGp.tempNode.map((el) => el.remove());
            });
        },
        addNode(latlng, map) {
            let node = L.icon({
                iconUrl: "/img/pt.png",
                iconSize: [16, 16],
            });
            node = L.marker(latlng, {
                icon: node,
            });
            node.addTo(map);
            return node;
        },
        drawPolygon() {
            let tempPolygonOpts = {
                color: "rgba(255, 0, 0, 0.85)",
                weight: 3,
                opacity: 0.85,
                interactive: false,
                // 添加量测信息属性，并开启
                showMeasurements: true,
                // 根据需要设置量测显示的参数
                measurementOptions: {
                    minDistance: 500
                },
            };
            let finalPolygonOpts = {
                color: "rgba(0, 255, 0, 0.85)",
                weight: 3,
                opacity: 0.85,
                // 添加量测信息属性，并开启
                showMeasurements: true,
                // 根据需要设置量测显示的参数
                measurementOptions: {
                    minDistance: 500,
                },
            };
            this.drawOn();
            this.map.on("click", (evt) => {
                this.tempGp.polygonNode.push([evt.latlng.lat, evt.latlng.lng]);
                this.tempGp.polygonNodeLen = this.tempGp.polygonNode.length;
                this.tempGp.tempNode.push(this.addNode(evt.latlng, this.map));
            });
            this.map.on("mousemove", (evt) => {
                if (this.tempGp.tempPolygon) this.tempGp.tempPolygon.remove();
                if (this.tempGp.polygonNodeLen == 1) {
                    this.tempGp.polygonNode[this.tempGp.polygonNodeLen] = [
                        evt.latlng.lat,
                        evt.latlng.lng,
                    ];
                    this.tempGp.tempPolygon = L.polygon(
                        this.tempGp.polygonNode,
                        tempPolygonOpts
                    );
                } else if (this.tempGp.polygonNodeLen >= 2) {
                    this.tempGp.polygonNode[this.tempGp.polygonNodeLen] = [
                        evt.latlng.lat,
                        evt.latlng.lng,
                    ];
                    this.tempGp.tempPolygon = L.polygon(
                        this.tempGp.polygonNode,
                        tempPolygonOpts
                    );
                }
                if (this.tempGp.tempPolygon) this.tempGp.tempPolygon.addTo(this.map);
            });
            this.map.on("dblclick", () => {
                let polygon = L.polygon(this.tempGp.polygonNode, finalPolygonOpts);
                polygon.addTo(this.map);
                let area = 1;
                // polygon.bindTooltip(`面积：${area}平方米`).openTooltip();
                this.overLayer.polygons.push(polygon);
                this.tempGp.polygonNode = [];
                this.tempGp.polygonNodeLen = 0;
                this.tempGp.tempPolygon.remove();
                this.tempGp.tempNode.map((el) => el.remove());
            });
        },
        drawCircle() {
            this.drawOn();
            let tempCenter,
                radius,
                isOK = false; //中心点是否确定好
            this.map.on("click", (evt) => {
                if (isOK) {
                    let circle = L.circle(this.tempGp.polygonNode[0], radius);
                    circle.addTo(this.map);
                    this.overLayer.polygons.push(circle);
                    this.tempGp.polygonNode = [];
                    this.tempGp.polygonNodeLen = 0;
                    this.tempGp.tempCircle.remove();
                    this.tempGp.tempNode.map((el) => el.remove());
                    isOK = false;
                } else {
                    this.tempGp.polygonNode.push([evt.latlng.lat, evt.latlng.lng]);
                    this.tempGp.polygonNodeLen = this.tempGp.polygonNode.length;
                    tempCenter = evt.latlng;
                    this.tempGp.tempNode.push(this.addNode(evt.latlng, this.map));
                    isOK = true;
                }
            });
            this.map.on("mousemove", (evt) => {
                if (isOK) {
                    if (this.tempGp.tempCircle) this.tempGp.tempCircle.remove();
                    if (this.tempGp.tempLine) this.tempGp.tempLine.remove();
                    radius = evt.latlng.distanceTo(tempCenter);
                    this.tempGp.tempLine = L.polyline(
                        [
                            [tempCenter.lat, tempCenter.lng],
                            [evt.latlng.lat, evt.latlng.lng],
                        ], {
                            stroke: true,
                            color: "#0085fb",
                            weight: 4,
                            opacity: 0.7, //不透明度
                        }
                    );
                    this.tempGp.tempLine.bindTooltip(radius + "米").openTooltip();
                    this.tempGp.tempCircle = L.circle(tempCenter, {
                        radius: radius,
                    });
                    if (this.tempGp.tempCircle) this.tempGp.tempCircle.addTo(this.map);
                    if (this.tempGp.tempLine) this.tempGp.tempLine.addTo(this.map);
                }
            });
            this.map.on("dblclick", () => {});
        },
    },
};
</script>

<style lang="less">
#map-container {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
}
</style>
